package cn.edu.baiyunu.myapplication.data.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import cn.edu.baiyunu.myapplication.data.dao.CategoryDao
import cn.edu.baiyunu.myapplication.data.dao.SavingsGoalDao
import cn.edu.baiyunu.myapplication.data.dao.SettingsDao
import cn.edu.baiyunu.myapplication.data.dao.TransactionDao
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.data.model.SavingsGoal
import cn.edu.baiyunu.myapplication.data.model.Settings
import cn.edu.baiyunu.myapplication.data.model.Transaction
import cn.edu.baiyunu.myapplication.data.util.Converters

/**
 * 应用数据库类
 */
@Database(
    entities = [
        Transaction::class,
        Category::class,
        Settings::class,
        SavingsGoal::class
    ],
    version = 2,
    exportSchema = false
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
    /**
     * 获取交易DAO
     */
    abstract fun transactionDao(): TransactionDao
    
    /**
     * 获取分类DAO
     */
    abstract fun categoryDao(): CategoryDao
    
    /**
     * 获取设置DAO
     */
    abstract fun settingsDao(): SettingsDao
    
    /**
     * 获取储蓄目标DAO
     */
    abstract fun savingsGoalDao(): SavingsGoalDao
    
    companion object {
        // 单例模式避免同时打开多个数据库实例
        @Volatile
        private var INSTANCE: AppDatabase? = null
        
        fun getDatabase(context: Context): AppDatabase {
            // 如果INSTANCE不为空，则返回它，否则创建数据库
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "app_database"
                )
                .fallbackToDestructiveMigration() // 当版本变更无法迁移时允许重建数据库
                .build()
                INSTANCE = instance
                instance
            }
        }
    }
} 